<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\common\model\Business;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品卡密管理
 *
 * @icon fa fa-circle-o
 */
class GoodsCards extends Backend
{

    /**
     * GoodsCards模型对象
     * @var \app\common\model\GoodsCards
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\GoodsCards;
        $this->view->assign("useStatusList", $this->model->getUseStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['goods','business','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('goods')->visible(['goods_title']);
				$row->getRelation('business')->visible(['business_name','business_code']);
                $row->getRelation('user')->visible(['nickname','mobile','avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        $row= $this->model->get($ids);
        if(!empty($row['user_id'])&&$row['use_status']==1){
            $this->error('用户已激活无需修改');
        }
        if(!empty($params['user_id'])){
            if($params['user_id']!=$row['user_id']){
               if($params['use_status']==0){
                   $this->error('已分配用户，激活状态需为已激活');
               }
            }
        }
        $params['id']=$ids;

        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function addcard()
    {
        if (false === $this->request->isPost()) {
            $goods_id= $this->request->param('goods_id',0);
            $this->assign('goods_id',$goods_id);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        if(empty($params['business_id'])){
            $this->error('请选择公司');
        }
        $business_code=(new Business())->where(['id'=>$params['business_id']])->value('business_code');
        if(empty($business_code)){
            $this->error('企业卡密固定码不能为空');
        }
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
             $cards=[];

           $c=$params['nums'];//生成1000组卡号密码
            if(!$c){
                $this->error('请填写生成卡密数量');
            }
            if(!is_numeric($c)&&$c<1){
                $this->error('请填写正确的生成卡密数量');
            }

            for($x=0;$x< $c;$x++){
                $cards[$x]['goods_id']=$params['goods_id'];
                $cards[$x]['business_id']=$params['business_id'];
                 $cards[$x]['goods_cards_no']=$this->getRandnumber();
                 $cards[$x]['goods_card_key']=$business_code.$this->makeCardPassword();
               }
            if(count($cards)>100){
                $num = 100;//每次导入条数
                $limit = ceil(count($cards)/$num);
                for($i=1;$i<=$limit;$i++){
                    $offset=($i-1)*$num;
                    $data=array_slice($cards,$offset,$num);
                    $result=  $this->model->saveAll($data);
                };
            }else{
                $result= $this->model->saveAll($cards);
            }



            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }

        $this->success();
    }

    function makeCardPassword($length = 7, $type = 4)
    {
        // 取字符集数组
        $number = range(0, 9);
        $lowerLetter = range('a', 'z');
        $upperLetter = range('A', 'Z');
        // 根据type合并字符集
        if ($type == 1) {
            $charset = $number;
        } elseif ($type == 2) {
            $charset = $lowerLetter;
        } elseif ($type == 3) {
            $charset = $upperLetter;
        } elseif ($type == 4) {
            $charset = array_merge($number, $lowerLetter);
        } elseif ($type == 5) {
            $charset = array_merge($number, $upperLetter);
        } elseif ($type == 6) {
            $charset = array_merge($lowerLetter, $upperLetter);
        } elseif ($type == 7) {
            $charset = array_merge($number, $lowerLetter, $upperLetter);
        } else {
            $charset = $number;
        }
        $str = '';
        // 生成字符串
        for ($i = 0; $i < $length; $i++) {
            $str .= $charset[mt_rand(0, count($charset) - 1)];
            // 验证规则
            if ($type == 4 && strlen($str) >= 2) {
                if (!preg_match('/\d+/', $str) || !preg_match('/[a-z]+/', $str)) {
                    $str = substr($str, 0, -1);
                    $i = $i - 1;
                }
            }
            if ($type == 5 && strlen($str) >= 2) {
                if (!preg_match('/\d+/', $str) || !preg_match('/[A-Z]+/', $str)) {
                    $str = substr($str, 0, -1);
                    $i = $i - 1;
                }
            }
            if ($type == 6 && strlen($str) >= 2) {
                if (!preg_match('/[a-z]+/', $str) || !preg_match('/[A-Z]+/', $str)) {
                    $str = substr($str, 0, -1);
                    $i = $i - 1;
                }
            }
            if ($type == 7 && strlen($str) >= 3) {
                if (!preg_match('/\d+/', $str) || !preg_match('/[a-z]+/', $str) || !preg_match('/[A-Z]+/', $str)) {
                    $str = substr($str, 0, -2);
                    $i = $i - 2;
                }
            }
        }
        return $str;
    }


//    function randCode($length = 6, $type = 0) {
//        $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
//        if ($type == 0) {
//            array_pop($arr);
//            $string = implode("", $arr);
//        } elseif ($type == "-1") {
//            $string = implode("", $arr);
//        } else {
//            $string = $arr[$type];
//        }
//        $count = strlen($string) - 1;
//        $code = '';
//        for ($i = 0; $i < $length; $i++) {
//            $code .= $string[rand(0, $count)];
//        }
//        return $code;
//    }
    /**
     * 生成不重复的随机数字
     * @param  int $start  需要生成的数字开始范围
     * @param  int $end    结束范围
     * @param  int $length 需要生成的随机数个数
     * @return number      生成的随机数
     */
    function getRandnumber ($start=0,$end=9,$length=8){
	//初始化变量为0
	$connt = 0;
	//建一个新数组
	$temp = array();
	while($connt < $length){
	//在一定范围内随机生成一个数放入数组中
	$temp[] = mt_rand ($start, $end);
	//$data = array_unique($temp);
	//去除数组中的重复值用了“翻翻法”，就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
	$data = array_flip(array_flip($temp));
	//将数组的数量存入变量count中
	$connt = count($data);
	}
    //为数组赋予新的键名
        shuffle($data);
      //数组转 字符串
        $str=implode(",", $data);
       //替换掉 逗号
         $number=str_replace(',', '', $str);

       return $number;
}

    public function export()
    {
        if ($this->request->isPost()) {
            $this->relationSearch = true;

            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');
            $excel = new Spreadsheet();
            $excel->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $excel->getDefaultStyle()->getFont()->setSize(12);
            $excel->getDefaultStyle()->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => Alignment::VERTICAL_CENTER,
                        'horizontal' => Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => Border::BORDER_THIN),
                    )
                ));

            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('标题');
            $whereIds = $ids == 'all' ? '1=1' : ['goods_cards.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $line = 1;
            $list = [];


            $xlsData =
                $this->model
                    ->with(['goods','business','user'])
                    ->where($whereIds)
                    ->where($where)
                    ->order($sort, $order)
                    ->select();


            /**
             * id,shop.name,username,estate,mobile,jointime
             */
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('产品卡密');  //设置当前sheet的标题

            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);


            $objSheet->setCellValue('A1', 'id')
                ->setCellValue('B1', '商品标题')
                ->setCellValue('C1', '企业名称')
                ->setCellValue('D1', '秘钥')
                ->setCellValue('E1', '激活用户昵称')
                ->setCellValue('F1', '激活用户手机号')
                ->setCellValue('G1', '激活状态')
                ->setCellValue('H1', '状态')
                ->setCellValue('I1', '创建时间')
            ;
            foreach ($xlsData as $k => $v) {
                $k += 2;
                /**
                 *  $row->getRelation('goods')->visible(['goods_title']);
                $row->getRelation('business')->visible(['business_name','business_code']);
                $row->getRelation('user')->visible(['nickname','mobile','avatar']);
                 */
                $objSheet->setCellValue('A' . $k, $v['id']);
                $objSheet->setCellValue('B' . $k, $v['goods']?$v['goods']['goods_title']:'');
                $objSheet->setCellValue('C' . $k, $v['business']?$v['business']['business_name']:'');
                $objSheet->setCellValue('D' . $k, $v['goods_card_key']);
                $objSheet->setCellValue('E' . $k, $v['user']?$v['user']['nickname']:'');
                $objSheet->setCellValue('F' . $k, $v['user']?$v['user']['mobile']:'');
                $objSheet->setCellValue('G'. $k, $v['use_status_text']);
                $objSheet->setCellValue('H'. $k, $v['status_text']);
                $objSheet->setCellValue('I' . $k, date('Y-m-d H:i:s', $v['createtime']));

            }

            /*--------------下面是设置其他信息------------------*/
            $title = date("Ymd-产品卡密");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            //   $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
            $objWriter->save('php://output');

        }


    }
}
